package app.biz.service.impl;

import app.biz.config.MongoDataSource;
import app.biz.service.EcgResultService;
import app.framework.util.ConcurrentUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/** Created by shadowedge on 2018/11/24. */
@Service
public class EcgResultServiceImpl implements EcgResultService {
  private static final Logger logger = LoggerFactory.getLogger(EcgResultServiceImpl.class);

  @Autowired MongoDataSource mongo;

    /*使用默认名称、默认线程池(10)*/
    static ListeningExecutorService resultPool = ConcurrentUtil.instance.getService();


    @Override
  public String saveResult(JSONObject result){
      Document doc = Document.parse(result.toString());
      //补充日期信息
      doc.append("created", new Date())
         .append("createdTime", System.currentTimeMillis());
      getCollection().insertOne(doc);
      return "true";
  }

    @Override
    public void saveResultAsync(JSONObject result) throws IOException {
        try {
            resultPool.submit(() ->saveResult(result));
        } catch (Exception e) {
          logger.error("结果保存失败！结果内容：{}", e, result.toJSONString());
        }
    }

    @Override
  public JSONObject findResultBySid(long sid) {
      Document doc =  getCollection().find(new Document("sid", sid)).first();
      if(null == doc){
          return new JSONObject();
      }
      //TODO: 直接构造过滤查询
      doc.remove("content");
      JSONObject result = new JSONObject();
      // 对查询结果进行提取封装
      // mongodb查询结果中会对long类型进行数据封装，如  "sid" : NumberLong(6616409131469153280)
      result.put("sid",doc.getLong("sid"));
      result.put("result",doc.get("result"));
      return result;
  }

    private MongoCollection<Document> getCollection() {
        return mongo.getCollecton("ecgresult");
    }
}
